<template>

    <!-- 添加或修改对话框 -->
    <el-dialog v-model="open" :title="form.categoryId?'修改数据':'新增数据'" width="900px" append-to-body >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
            <!-- <el-col v-if="tag === 0" :span="24">
            <el-form-item label="上级节点" prop="superId">
                <el-select v-model="form.superId" :data="form"
                :props="{ value:'categoryId',label: 'categoryName' , children: 'children'}" value-key="categoryId"
                placeholder="选择上级分类" check-strictly />
            </el-form-item>
            </el-col> -->
            <el-form-item  label="上级节点" prop="superId">
                {{form.superName}}
            </el-form-item>

            <el-form-item label="图片" prop="categoryImageSrc">
                <el-upload
                    class="avatar-uploader"
                    :action="imageUploadUrl"
                    :headers="data.header"
                    :data="data.ossdata"
                    name="imgFile"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="form.categoryImageSrc" :src="form.categoryImageSrc" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
            </el-form-item>



            <el-form-item label="名称" prop="categoryName">
                <el-input v-model="form.categoryName" placeholder="请输入名称" />
            </el-form-item>


        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
import { reactive, ref,getCurrentInstance, ComponentInternalInstance  } from 'vue';
import { type FormRules, type FormInstance, ElMessage, type UploadFile  } from 'element-plus';
// TypeScript数据模型，约束只能传变量
// 引用后台的api
import { getToken } from '@/utils/auth';
import { FormReq, Resp ,StoreCategoryReq } from '@/api/app/typescript/StoreCategory';
import { addApi, category, getByIdApi, updateApi } from '@/api/app/store/category';
// 获取当前vue3的页面this对象转换为proxy代理，查询 sys_dict_data表中的值
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const categoryOptions = ref<any>([]);

//图片上传地址
const imageUploadUrl =ref(import.meta.env.VITE_APP_BASE_API+'/oss/uploadImg');
const token=getToken();
//配置请求头的令牌
const header={
    header: {
        'Authorization': token
    }
} ;

//自己的定义额外参数
const data = reactive({
    header: {
        'Authorization': token
    },
    ossdata: {
        fatherPath:'images'
    }
});
const open = ref(false);
//得到数据表单form样式对象
const formRef = ref<FormInstance>();

//声明子组件的自定义事件 https://cn.vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
const emit = defineEmits(['refreshDataList']);

// 定义表单对象
const form = ref<FormReq>({ 
    categoryId: undefined,
    superId: undefined,
    superName: '',
    categoryName: '',
    categoryImageSrc: ''    
});


// 表单验证
const rules = reactive<FormRules>({
    categoryName: [
        { required: true, message: '该值不能为空', trigger: 'blur' }
    ]
});

//对话框保存按钮
const submitForm = () => {
    formRef.value.validate((valid: boolean) => {
        //验证不成功
       	if (!valid) {
       		return false;
       	}

        //修改
        if(form.value.categoryId!== undefined){
            updateApi(form.value).then(resp=>{
                ElMessage.success({
                    message: '修改成功',
                    duration: 500,
                    onClose: () => {
                        //关闭弹窗
                        open.value = false;
                        //调用重新查询数据操作
                        emit('refreshDataList');
                    }
                });

            });
        }else{
            //新增
            addApi(form.value).then(resp=>{
                ElMessage.success({
                    message: '新增成功',
                    duration: 500,
                    onClose: () => {
                        //关闭弹窗
                        open.value = false;
                        //调用重新查询数据操作
                        emit('refreshDataList');
                    }
                });

            });
        }

    });

};

//对话框取消按钮
const cancel = () => {
    open.value = false;
    resetFrom();
};


// 重置表单
const resetFrom = () => {
    // 清空表单样式
    if (formRef.value){
        formRef.value.resetFields();
    }
    // 重置值
    form.value = {
        
        categoryId: undefined,
        superId: undefined,
        superName: '',
        categoryImageSrc: '',
        categoryName:'',
    };
};

//判断如果是修改操作，就要查询数据库，还原数据,要暴露出去
const init = (categoryId?: number|undefined,tag?: number) => {

    // 重置表单数据
    resetFrom();
    // id 存在则为修改
    if (tag === 1) {
        getByIdApi(categoryId).then(resp=> {
            const data:Resp=resp.data;

            const dataObj:FormReq=JSON.parse(JSON.stringify(data));

            form.value=dataObj ;
        });
    }else{
        //新增 
        //查找上级节点的信息
        
        if(categoryId){
            form.value.superId=categoryId;
            getByIdApi(categoryId).then(resp=> {
                form.value.superName= resp.data.categoryName ; 
            });
        }else{
            form.value.superId=0;
            form.value.superName='根节点';
        }
        
    }
    open.value = true;
           
};
 

// 上传图片时检查
function  beforeAvatarUpload(file) {
    console.log(file);
    //允许的图片类型
    const imgType = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif');
    //文件大小3M
    const imgLimit= (file.size / 1024 / 1024) < 3;
    if (!imgType) {
        ElMessage.error("只允许jpg、png、gif格式的图片");
        return false;
    }
    if (!imgLimit) {
        ElMessage.error("上传的图片大小不能超过3MB");
        return false;
    }

    return true;
}

/** 上传图片 */
function handleAvatarSuccess(res, file)  {
    console.log(res);
    form.value.categoryImageSrc=res.data;
};

//https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
defineExpose({
   	init
});

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
